import React from "react";
import "./style.css";
class App extends React.Component {
  state = {
    list: [
      {
        title: "item-1",
        time: new Date().toLocaleString(),
        state: false,
        id: "1",
      },
      {
        title: "item-2",
        time: new Date(+new Date() + 10000).toLocaleString(),
        state: false,
        id: "2",
      },
      {
        title: "item-3",
        time: new Date(+new Date() + 20000).toLocaleString(),
        state: false,
        id: "3",
      },
    ],
  };
  handleKeyDown(e) {
    if (e.keyCode === 13) {
      const { list } = this.state;

      this.setState({
        list: [
          ...list,
          {
            title: e.target.value,
            time: new Date().toLocaleString(),
            state: false,
            id: Math.random().toString().slice(2),
          },
        ],
      });
    }
  }
  handleDelete(v) {
    this.setState({
      list: this.state.list.filter((item) => item.id !== v.id),
    });
  }
  handleFinish(v) {
    const { list } = this.state;
    const item = list.find((item) => item.id === v.id);
    item.state = true;
    this.setState({
      list: [...list],
    });
  }
  render() {
    const { list } = this.state;
    return (
      <div>
        <input type="text" onKeyDown={(e) => this.handleKeyDown(e)} />
        <ul>
          {list.map((v, i) => {
            return (
              <li key={i} className={v.state ? "active" : ""}>
                <span>{v.title}</span>
                <span>{v.time}</span>
                <button onClick={() => this.handleDelete(v)}>删除</button>
                <button onClick={() => this.handleFinish(v)}>完成</button>
              </li>
            );
          })}
        </ul>
      </div>
    );
  }
}

export default App;
